package com.pxene.dmp.job;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pxene.dmp.bean.SearchWord;
import com.pxene.dmp.bean.SearchWord.Content;
import com.pxene.dmp.common.DateUtils;
import com.pxene.dmp.common.KVRequester;
import com.pxene.dmp.common.KVUrlGenerator;
import com.pxene.dmp.constant.BaseConstant;
import com.pxene.dmp.job.task.SearchWordTask;

// 启动task
// 创建KVRequester
public class SearchWordJob extends BaseJob implements Runnable {
	// 多个job公用一个线程池执行task
	private final ExecutorService pool;
	// 每个job完成都-1，计数到0关闭线程池
	private final CountDownLatch latch;

	private Log log = LogFactory.getLog(SearchWordJob.class);
	private BufferedWriter bw;

	public SearchWordJob(ExecutorService pool, CountDownLatch latch, BufferedWriter bw) {
		this.pool = pool;
		this.latch = latch;
		this.bw = bw;
	}

	@Override
	public void run() {
		String date = System.getProperty("date");
		// 创建输出文件
		BufferedWriter writer = createFileWriter("searchword_" + date + ".dat");
		// 请求数据总数
		Map<String, String> params0 = new HashMap<String, String>();
		int sum = 0;
		for (int inx = BaseConstant.STARTINDEX; inx <= BaseConstant.ENDINDEX; inx++) {
			params0.put("index", inx + "|0");
			params0.put("date", date);
			SearchWord word = null;
			for (int i = 0; i < retry; i++) {
				String url = KVUrlGenerator.getCustUrl(BaseConstant.API_GET_SEARCHWORD);
				KVRequester reqer0 = new KVRequester(url, params0, bw);
				word = (SearchWord) reqer0.execute(SearchWord.class);
				reqer0.close();
				if (word != null && word.getCode() == 200) {
					break;
				}
				try {
					bw.write("[ERROR] " + DateUtils.getNowFormat("yyyy-MM-dd HH:mm:ss") + " ["
							+ Thread.currentThread().getName() + "] [" + SearchWordJob.class.getName() + "] "
							+ "<=ee-debug=>" + "connection failed, this is the:" + i + "time to try connection!"
							+ "\n");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			CountDownLatch taskLatch = null;
			// 请求成功
			if (word != null && word.getCode() == 200) {
				Content content = word.getData();
				// 如果有总数，则循环总数次
				if (content != null) {
					int total = 0;
					try {
						total = Integer.parseInt(content.getImsi());
					} catch (NumberFormatException e) {
						try {
							bw.write("[ERROR] " + DateUtils.getNowFormat("yyyy-MM-dd HH:mm:ss") + " ["
									+ Thread.currentThread().getName() + "] [" + SearchWordJob.class.getName() + "] "
									+ "<=ee-debug=>" + "total cannot parse Number Exception:" + e + "\n");
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}
					sum += total;
					log.info(BaseConstant.LOG_PREFIX + inx + "|total=" + total);
					try {
						bw.write("[TOTAL] " + DateUtils.getNowFormat("yyyy-MM-dd HH:mm:ss") + " ["
								+ Thread.currentThread().getName() + "] [" + SearchWordJob.class.getName() + "] "
								+ "<=ee-debug=>" + inx + "|total=" + total + "\n");
					} catch (IOException e) {
						e.printStackTrace();
					}
					taskLatch = new CountDownLatch(total);
					for (int i = 1; i <= total; i++) {
						pool.execute(new SearchWordTask(inx + "|" + i, date, writer, taskLatch, bw));
					}
				}
			}
			if (taskLatch != null) {
				try {
					taskLatch.await();
				} catch (Exception e) {
					log.error(BaseConstant.LOG_PREFIX + "TaskLatch await Exception", e);
					try {
						bw.write("[ERROR] " + DateUtils.getNowFormat("yyyy-MM-dd HH:mm:ss") + " ["
								+ Thread.currentThread().getName() + "] [" + SearchWordJob.class.getName() + "] "
								+ "<=ee-debug=>" + "TaskLatch await Exception" + e + "\n");
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
		}
		try {
			bw.write("[SUM] " + DateUtils.getNowFormat("yyyy-MM-dd HH:mm:ss") + " [" + Thread.currentThread().getName()
					+ "] [" + SearchWordJob.class.getName() + "] " + "<=ee-debug=>" + "sum=" + sum + "\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
		closeFileWriter(writer);
		latch.countDown();
	}

	public static void main(String[] args) {
		String urlll = KVUrlGenerator.getCustUrl(BaseConstant.API_GET_SEARCHWORD);
		System.out.println(urlll);
	}
}
